import React, {FC, CSSProperties, useState, createContext, Children, cloneElement} from "react";
import classNames from 'classnames';
import {MenuItemProps} from "./menuItem";

type MenuMode = 'vertical' | 'horizontal'

export interface MenuProps {
    defaultIndex?: string;
    className?: string;
    mode?: MenuMode;
    style?: CSSProperties;
    onSelect?: (selectedIndex: string) => void;
}

interface MenuCtx {
    index: string;
    onSelect?: (selectedIndex: string) => void;
}

export const MenuContext = createContext<MenuCtx>({index: '0'});

export const Menu: FC<MenuProps> = (props) => {
    const {defaultIndex, className, mode, style, onSelect, children} = props;
    const [currentIndex, setCurrent] = useState(defaultIndex)

    const classes = classNames('menu', className, {
        'menu-vertical': mode === 'vertical',
        'menu-horizontal': mode === 'horizontal'
    })

    const handleClick = (index: string) => {
        setCurrent(index);
        if (onSelect) {
            onSelect(index)
        }
    }

    const providerContext: MenuCtx = {
        index: currentIndex ? currentIndex : '0',
        onSelect: handleClick,
    }

    const renderChildren = () => {
        return Children.map(children, (child, index) => {
            const childElement = child as React.FunctionComponentElement<MenuItemProps>;
            const {displayName} = childElement.type;

            if (displayName === 'MenuItem') {
                return cloneElement(childElement, {
                    index: index.toString()
                })
            } else {
                console.error("Warning: Menu has a child which is not a MenuItem component")
            }
        })
    }

    return (
        <ul className={classes} style={style}>
            <MenuContext.Provider value={providerContext}>
                {renderChildren()}
            </MenuContext.Provider>
        </ul>
    )
}

Menu.defaultProps = {
    defaultIndex: '0',
    mode: 'horizontal'
}

export default Menu;